package com.infodms.dms.actions.sales.marketmanage.planmanage;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.infodms.dms.actions.common.FileUploadManager;
import com.infodms.dms.bean.AclUserBean;
import com.infodms.dms.common.Constant;
import com.infodms.dms.common.DateUtil;
import com.infodms.dms.common.ErrorCodeConstant;
import com.infodms.dms.common.materialManager.MaterialGroupManagerDao;
import com.infodms.dms.dao.sales.marketmanage.plancommon.ActivitiesCommonDao;
import com.infodms.dms.dao.sales.marketmanage.planmanage.ActivitiesPlanManageDao;
import com.infodms.dms.dao.sales.marketmanage.planmanage.ActivitiesSummaryReportDao;
import com.infodms.dms.exception.BizException;
import com.infodms.dms.po.TtCamCampaignCostPO;
import com.infodms.dms.po.TtCamMediaCostPO;
import com.infodms.dms.po.TtCampaignExecutePO;
import com.infodms.dms.po.TtCampaignPO;
import com.infodms.dms.po.TtCampaignSpaceExecutePO;
import com.infodms.dms.po.TtCampaignTargetPO;
import com.infodms.dms.util.CommonUtils;
import com.infoservice.mvc.context.ActionContext;
import com.infoservice.mvc.context.RequestWrapper;
import com.infoservice.po3.bean.PageResult;

public class ActivitiesSummaryReport {
	
	public Logger logger = Logger.getLogger(ActivitiesPlanReport.class);   
	ActivitiesSummaryReportDao dao  = ActivitiesSummaryReportDao.getInstance();
	private ActionContext act = ActionContext.getContext();
	
	private final String initUrl = "/jsp/sales/marketmanage/planmanage/activitiesSummaryReportSearch.jsp";
	private final String addUrl = "/jsp/sales/marketmanage/planmanage/activitiesSummaryReport.jsp";
	
	/**
	 * 活动执行方案提报页面初始化
	 */
	public void activitiesSummaryReportInit(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			List<Map<String, Object>> areaList = MaterialGroupManagerDao.getPoseIdBusiness(logonUser.getPoseId().toString());
			act.setOutData("areaList", areaList);
			act.setForword(initUrl);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"活动方案提报页面初始化");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	/**
	 * 活动执行方案提报查询
	 */
	public void activitiesSummaryReportQuery(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			RequestWrapper request = act.getRequest();
			Long poseId = logonUser.getPoseId() ;
			String areaId=request.getParamValue("areaId");
			String campaignNo = request.getParamValue("campaignNo");			//方案编号
			String campaignName = request.getParamValue("campaignName");		//方案名称
			String campaignSubject = request.getParamValue("campaignSubject");	//活动主题
			String campaignType = request.getParamValue("campaignType");		//活动类别
			String startDate = request.getParamValue("startDate");				//开始时间
			String endDate = request.getParamValue("endDate");					//结束时间
			String dealerId = logonUser.getDealerId().toString();
			Integer curPage = request.getParamValue("curPage") !=null ? Integer.parseInt(request.getParamValue("curPage")) : 1;
			PageResult<Map<String, Object>> ps= dao.activitiesPlanReportQuery(poseId, areaId,campaignNo, campaignName, campaignSubject, campaignType, startDate, endDate, dealerId, curPage, Constant.PAGE_SIZE);
			act.setOutData("ps", ps);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"活动执行方案提报查询");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	/**
	 * 活动总结提报页面初始化
	 */
	public void showActivitiesSummaryReportPage(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		ActivitiesCommonDao cdao=ActivitiesCommonDao.getInstance();
		try {
			RequestWrapper request = act.getRequest();
			String campaignId=request.getParamValue("campaignId")==null?"":request.getParamValue("campaignId");
			String executeId=request.getParamValue("executeId")==null?"":request.getParamValue("executeId");
			//参数MAP
			Map<String, Object> conMap=new HashMap<String, Object>();
			conMap.put("campaignId", campaignId);
			conMap.put("executeId", executeId);
			conMap.put("costId", "");
			conMap.put("targetId", "");
			ActivitiesPlanManageDao dddao = ActivitiesPlanManageDao.getInstance();
			String modelName = dddao.getModelName(campaignId);
			//查品牌
			Map<String, Object> map = dao.selectPinPai();
			String groupName = map.get("GROUP_NAME").toString();
			//查业务范围
			List<Map<String, Object>> areaList = MaterialGroupManagerDao.getDealerBusiness(logonUser.getPoseId().toString());
			//方案详细信息
			Map<String, Object> planMap=cdao.selectCampaignDetial(executeId);
			planMap.put("PROD_NAME", modelName);
			//附件列表
			List<Map<String, Object>> attachmentList=cdao.getAttachInfo(executeId);
			// 媒体投放费用
			List<Map<String, Object>> mediaList=cdao.selectMediaCost(conMap);
			// 市场活动费用
			List<Map<String, Object>> capList=cdao.selectCampaignCost(conMap);
			// 活动总结
			Map<String, Object> targetMap=cdao.selectCampaignTarget(conMap);
			List<Map<String, Object>> mycheckList = cdao.getMyCheckInfo(executeId,campaignId);
			String dealerIds=logonUser.getDealerId();
			List<Map<String, Object>> amountList1 = dao.queryDealerCost(dealerIds);
			List<Map<String, Object>> amountList2 = dao.queryAreaCost(dealerIds);
			List<Map<String, Object>> amountList3 = dao.queryOemCost();
			
			String type = "" ;
			if(capList.size()>0 ){
				type = capList.get(0).get("COST_TYPE").toString() ;
			}
			if(mediaList.size()>0){
				type = mediaList.get(0).get("COST_TYPE").toString() ;
			}
			act.setOutData("type", type) ;
			
			act.setOutData("amountList1", amountList1);
			act.setOutData("amountList2", amountList2);
			act.setOutData("amountList3", amountList3);
			act.setOutData("targetMap", targetMap);
			act.setOutData("planMap", planMap);
			act.setOutData("attachmentList", attachmentList);
			act.setOutData("mediaList", mediaList);
			act.setOutData("capList", capList);
			act.setOutData("areaList", areaList);
			act.setOutData("groupName", groupName);
			act.setOutData("mycheckList", mycheckList);
			act.setForword(addUrl);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"活动方案提报新增页面初始化");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/**
	 * 活动总结提报页面初始化
	 */
	public void showActivitiesSummaryReport(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		ActivitiesCommonDao cdao=ActivitiesCommonDao.getInstance();
		try {
			RequestWrapper request = act.getRequest() ;
			String campaignId = CommonUtils.checkNull(request.getParamValue("campaignId")) ;
			String executeId = CommonUtils.checkNull(request.getParamValue("executeId")) ;
			
			TtCampaignPO tc = new TtCampaignPO() ;
			tc.setCampaignId(Long.parseLong(campaignId)) ;
			
			tc = (TtCampaignPO)dao.select(tc).get(0) ;
			
			String camType = tc.getCampaignType().toString() ;
			
			//市场活动执行方案
			//活动评估
			String evaluateDesc = request.getParamValue("EVALUATE_DESC");
			//建议及整改措施
			String adviceDesc = request.getParamValue("ADVICE_DESC");
			//来电来店数
			String callsHousesCntAct = request.getParamValue("CALLS_HOUSES_CNT_ACT");
			//信息留存量
			String reserveCntAct = request.getParamValue("RESERVE_CNT_ACT");
			//订单量
			String orderCntAct = request.getParamValue("ORDER_CNT_ACT");
			//交车量
			String deliveryCntAct = request.getParamValue("DELIVERY_CNT_ACT");
			//更新市场活动目标
			String targetId = request.getParamValue("TARGET_ID");
			//附件添加
			String []fjids = request.getParamValues("fjids");
			
			int updateLen = 0 ;
			List<TtCampaignExecutePO> tce = null ;
			if (Constant.CAMPAIGN_TYPE_03.toString().equals(camType)) {
				TtCampaignSpaceExecutePO oldTcse = new TtCampaignSpaceExecutePO() ;
				oldTcse.setSpaceId(Long.parseLong(executeId)) ;
				TtCampaignSpaceExecutePO newTcse = new TtCampaignSpaceExecutePO() ;
				newTcse.setEvaluateDesc(evaluateDesc) ;
				newTcse.setActiviceSummaryDesc(adviceDesc) ;//活动总计评估
				newTcse.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_08) ;
				
				dao.update(oldTcse, newTcse);
				
				FileUploadManager.fileUploadByBusiness(executeId, fjids, logonUser);
				
				TtCampaignExecutePO execonpo = new TtCampaignExecutePO();
				execonpo.setCampaignId(Long.parseLong(campaignId)) ;
				TtCampaignExecutePO exepo = new TtCampaignExecutePO();
				exepo.setEvaluateDesc(evaluateDesc) ;
				exepo.setActiviceSummaryDesc(adviceDesc) ;//活动总计评估
				exepo.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_08) ;
				
				updateLen = dao.update(execonpo, exepo) ;
				
				tce = dao.select(execonpo) ;
			} else {
				TtCampaignExecutePO execonpo=new TtCampaignExecutePO();
				execonpo.setExecuteId(new Long(executeId));
				TtCampaignExecutePO exepo=new TtCampaignExecutePO();
				exepo.setEvaluateDesc(evaluateDesc);
				exepo.setActiviceSummaryDesc(adviceDesc);//活动总计评估
				exepo.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_07);
				
				dao.update(execonpo, exepo);
				
				FileUploadManager.fileUploadByBusiness(executeId, fjids, logonUser);
			}
			
			TtCampaignTargetPO tarconpo = new TtCampaignTargetPO();
			tarconpo.setTargetId(new Long(targetId));
			TtCampaignTargetPO tarpo = new TtCampaignTargetPO();
			tarpo.setCallsHousesCntAct(new Integer(callsHousesCntAct));
			tarpo.setReserveCntAct(new Integer(reserveCntAct));
			tarpo.setOrderCntAct(new Integer(orderCntAct));
			tarpo.setDeliveryCntAct(new Integer(deliveryCntAct));
			tarpo.setUpdateBy(logonUser.getUserId());
			SimpleDateFormat dateformat1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
			Date date = dateformat1.parse( dateformat1.format(new Date())); 
			tarpo.setUpdateDate(date);
			
			dao.update(tarconpo, tarpo);
			
			for(int i=0; i<updateLen; i++) {
				executeId = tce.get(i).getExecuteId().toString() ;
				
				tarconpo = new TtCampaignTargetPO();
				tarconpo.setExecuteId(Long.parseLong(executeId)) ;
				tarpo = new TtCampaignTargetPO();
				tarpo.setCallsHousesCntAct(new Integer(callsHousesCntAct));
				tarpo.setReserveCntAct(new Integer(reserveCntAct));
				tarpo.setOrderCntAct(new Integer(orderCntAct));
				tarpo.setDeliveryCntAct(new Integer(deliveryCntAct));
				tarpo.setUpdateBy(logonUser.getUserId());
				dateformat1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
				date = dateformat1.parse( dateformat1.format(new Date())); 
				tarpo.setUpdateDate(date);
				
				dao.update(tarconpo, tarpo);
				
				FileUploadManager.fileUploadByBusiness(executeId, fjids, logonUser);
			}
			
			//更新媒体投放费用和市场活动费用
			Enumeration<String> enumeration = request.getParamNames();
			String camCostId="";
			String medCostId="";
			String tmp="";
			while(enumeration.hasMoreElements()){
				tmp=enumeration.nextElement();
				if(tmp.indexOf("CAM")!=-1){
					camCostId=tmp.substring(tmp.indexOf("CAM")+3,tmp.length());
					String camRealCost=request.getParamValue(tmp);
					TtCamCampaignCostPO conpo=new TtCamCampaignCostPO();
					conpo.setCostId(new Long(camCostId));
					TtCamCampaignCostPO po=new TtCamCampaignCostPO();
					po.setRealCost(new Double(camRealCost));
					po.setUpdateBy(logonUser.getUserId());
					po.setUpdateDate(new Date());
					
					dao.update(conpo, po);
					
					for(int i=0; i<updateLen; i++) {
						executeId = tce.get(i).getExecuteId().toString() ;
						
						conpo=new TtCamCampaignCostPO();
						conpo.setExecuteId(Long.parseLong(executeId));
						conpo.setSpaceCostId(Long.parseLong(camCostId)) ;
						po=new TtCamCampaignCostPO();
						po.setRealCost(new Double(camRealCost));
						po.setUpdateBy(logonUser.getUserId());
						po.setUpdateDate(new Date());
						
						dao.update(conpo, po);
					}
				}else if(tmp.indexOf("MED")!=-1){
					medCostId=tmp.substring(tmp.indexOf("MED")+3,tmp.length());
					String medRealCost=request.getParamValue(tmp);
					TtCamMediaCostPO conpo=new TtCamMediaCostPO();
					conpo.setCostId(new Long(medCostId));
					TtCamMediaCostPO po=new TtCamMediaCostPO();
					po.setRealCost(new Double(medRealCost));
					po.setUpdateBy(logonUser.getUserId());
					po.setUpdateDate(new Date());
					
					dao.update(conpo, po);
					
					for(int i=0; i<updateLen; i++) {
						executeId = tce.get(i).getExecuteId().toString() ;
						
						conpo=new TtCamMediaCostPO();
						conpo.setExecuteId(Long.parseLong(executeId));
						conpo.setSpaceCostId(Long.parseLong(medCostId)) ;
						po=new TtCamMediaCostPO();
						po.setRealCost(new Double(medRealCost));
						po.setUpdateBy(logonUser.getUserId());
						po.setUpdateDate(new Date());
						
						dao.update(conpo, po);
					}
				}else{
					continue;
				}
			}
			
			act.setOutData("returnValue", 1);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"活动方案总结提报");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
}
